Component({
  properties: {
    // 显示时长（单位：ms）
    duration: {
      type: Number,
      value: 2000
    },
    // 类型映射样式
    type: {
      type: String,
      value: 'info',
      observer: '_checkType'
    },
    showIcon: {
      type: Boolean,
      value: false
    },
    iconClass: {
      type: String,
      value: ''
    },
  },

  data: {
    show: false,
    content: '',
    typeClass: '',
    iconList: {
      info: 'icon-tanhao',
      success: 'icon-correct_2',
      warning: 'icon-Alert',
      error: 'icon-close1'
    }
  },

  methods: {
    // 显示Toast
    show(options) {
      const { content, type, duration, showIcon = false } = options
      let typeClass = type || 'info'
      this.setData({
        show: true,
        content,
        showIcon,
        typeClass: typeClass,
        iconClass: this.data.iconList[typeClass],
        _animation: this._createAnimation(1)
      })
      this.timer = setTimeout(() => this.hide(), duration || this.properties.duration)
    },

    // 隐藏Toast
    hide() {
      this.setData({
        _animation: this._createAnimation(0)
      })
      setTimeout(() => {
        this.setData({ show: false })
        clearTimeout(this.timer)
      }, 300)
    },

    // 创建动画对象[2,7](@ref)
    _createAnimation(opacity) {
      return wx.createAnimation({
        duration: 300,
        timingFunction: 'ease'
      }).opacity(opacity).step().export()
    },

    // 验证类型有效性
    _checkType(newVal) {
      const validTypes = ['info', 'success', 'warning', 'error']
      if (!validTypes.includes(newVal)) {
        console.warn(`Invalid toast type: ${newVal}`)
      }
    }
  }
})